package com.example.fengshoutong.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.fengshoutong.MainApplication;
import com.example.fengshoutong.R;
import com.example.fengshoutong.bean.Good;
import com.example.fengshoutong.greendao.GoodDao;
import com.example.fengshoutong.utils.FragmentUtils;
import com.example.fengshoutong.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * 发布商品页面
 */
public class PublishGoodFragment extends Fragment {
    // 打开相册申请码
    private static final int OPEN_GALLERY_REQUEST_CODE = 1;
    private final String[] type = {"水果蔬菜", "米面粮油", "农资农具"};
    // 分类下拉列表
    private Spinner spinner_type;
    // 商品主页图
    private ImageView image_picture;
    // 商品标题编辑栏
    private EditText edit_title;
    // 商品内容编辑栏
    private EditText edit_content;
    // 商品价格编辑栏
    private EditText edit_price;
    // 商品地址编辑栏
    private EditText edit_address;
    // 商品数据库
    private GoodDao goodDao;
    // 选中的商品类型
    private int selectGoodType;
    // 从相册选择后保存到本地缓存的图像Uri
    private Uri selectImageUri;
    // Android13版本申请从相册选择图片的方法
    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取商品数据库
        goodDao = MainApplication.getInstance().getGoodDaoSession().getGoodDao();
        // Android13版本打开相册的方法
        if (Build.VERSION.SDK_INT >= 33) {
            pickMedia = registerForActivityResult(
                    new ActivityResultContracts.PickVisualMedia(), uri -> {
                        if (uri != null) {
                            // 保存图片到本地缓存
                            try {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                                saveImageToInternalStorage(bitmap);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            );
        }

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_publish_good, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }

    private void initView() {
        image_picture = getView().findViewById(R.id.image_picture);
        edit_title = getView().findViewById(R.id.edit_title);
        edit_content = getView().findViewById(R.id.edit_content);
        edit_price = getView().findViewById(R.id.edit_price);
        edit_address = getView().findViewById(R.id.edit_address);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, type);
        spinner_type = getView().findViewById(R.id.spinner_type);
        spinner_type.setAdapter(arrayAdapter);
        spinner_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 由于分类里面推荐是在第一个，position为0，但是下拉列表没有加入推荐类型，所以全部position后移1位，第一个应该是水果蔬菜
                selectGoodType = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        getView().findViewById(R.id.btn_add_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 33) {
                    // Android13打开相册的方法
                    pickMedia.launch(new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build());
                } else {
                    // 旧版打开相册选择图片的方法
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "images/*");
                    startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
                }

            }
        });
        getView().findViewById(R.id.image_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentUtils.getInstance().switchFragment(R.id.nav_home);
            }
        });
        getView().findViewById(R.id.btn_publish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String label = edit_title.getText().toString();
                String content = edit_content.getText().toString();
                int type = selectGoodType;
                // 格式化显示价格，精确到小数点后2位
                DecimalFormat df = new DecimalFormat("#.00");
                String formattedNumber = df.format(Double.parseDouble(edit_price.getText().toString()));
                String price = "¥ " + formattedNumber;
                if (selectImageUri == null) {
                    ToastUtils.getInstance().makeToast("请添加图片！");
                    return;
                }
                String imageUri = selectImageUri.toString();
                String address = edit_address.getText().toString();
                if (label == null || content == null || price == null || imageUri == null || address == null) {
                    ToastUtils.getInstance().makeToast("请填写完整信息！");
                    return;
                }
                // 保存商品到商品数据库中
                Good good = new Good(label, content, type, price, imageUri, address);
                goodDao.insert(good);
                ToastUtils.getInstance().makeToast("发布成功！");
                FragmentUtils.getInstance().switchFragment(R.id.nav_home);
            }
        });
    }

    /**
     * 旧版的打开相册选择图片的回调
     *
     * @param requestCode The integer request code originally supplied to
     *                    startActivityForResult(), allowing you to identify who this
     *                    result came from.
     * @param resultCode  The integer result code returned by the child activity
     *                    through its setResult().
     * @param data        An Intent, which can return result data to the caller
     *                    (various data can be attached to Intent "extras").
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_GALLERY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 保存相册图片到本地缓存中
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
                    saveImageToInternalStorage(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 保存相册图片到应用缓存中
     *
     * @param bitmap
     */
    private void saveImageToInternalStorage(Bitmap bitmap) {
        FileOutputStream fos = null;
        // 根据时间给图像文件取名，避免重名导致显示不对
        String path = getActivity().getFilesDir() + "/image_" + new Date() + ".jpg";
        try {
            fos = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 获取本地缓存的图像Uri
        selectImageUri = Uri.fromFile(new File(path));
        // 保存完毕后在主线程更新显示图像
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                image_picture.setImageURI(selectImageUri);
            }
        });
    }

}